package com.peng.rpc.socket.server;

import com.peng.rpc.common.server.AbstractRpcServer;
import com.peng.rpc.common.server.RequestHandler;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import com.peng.rpc.provider.DefaultServiceProvider;
import com.peng.rpc.registry.NacosServiceRegistry;
import com.peng.rpc.registry.ShutDownHook;
import com.peng.rpc.serializer.CommonSerializer;
import com.peng.rpc.util.SingletonFactory;
import com.peng.rpc.util.ThreadPoolFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * 使用ServerSocket阻塞监听客户端的请求
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/2/27 20:01
 */
@Slf4j
public class SocketRpcServer extends AbstractRpcServer {

    private final ExecutorService threadPool;
    private final RequestHandler requestHandler = SingletonFactory.getSingletonInstance(RequestHandler.class);
    private final CommonSerializer serializer;
    private volatile boolean isStarted = false;

    public SocketRpcServer(String host, int port) {
        this(DEFAULT_SERIALIZER, host, port);
    }

    public SocketRpcServer(int serializerCode, String host, int port) {
        this.serializer = CommonSerializer.getSerializerByCode(serializerCode);
        this.host = host;
        this.port = port;
        threadPool = ThreadPoolFactory.createDefaultThreadPool("socket-server-poll");
        serviceProvider = new DefaultServiceProvider();
        serviceRegistry = new NacosServiceRegistry();
        servicesScan();
    }

    @Override
    public void start() {
        isStarted = true;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            if (serializer == null) {
                log.error("未设置序列化器，无法发送请求");
                throw new RpcException(RpcError.SERIALIZER_UNSETTED);
            }
            log.info("服务器启动在端口【{}】", port);
            ShutDownHook.addShutDownHooks();
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                log.info("接收到来自客户端:【{}】的连接，开始处理请求", socket.getInetAddress());
                threadPool.execute(new SocketRequestHandlerThread(socket, requestHandler, serializer));
            }
            threadPool.shutdown();
        } catch (IOException e) {
            log.error("服务器处理请求发生错误：{}", e.getMessage());
        }
    }

}
